package main

import (
	"fmt"
	"os"
	"syscall"
	"gitee.com/cdevel/dfs-go-lite/dfs"
)

func main() {
	// Initialize the DFS instance
	dfsInstance := &dfs.DFS{}
	err := dfsInstance.Init()
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to initialize DFS: %v\n", err)
		os.Exit(1)
	}

	// connect to the pool
	pool := "xpool"
	sys := "daos_server"
	cont := "xdata"
	flag := os.O_CREATE | os.O_RDWR

	err = dfsInstance.Connect(pool, sys, cont, flag, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to connect DFS: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("Connected to DFS")


	// open or create a DFS directory
	dir1 := "dir1"
	mode := syscall.S_IFDIR | syscall.S_IWUSR | syscall.S_IRUSR
	flags := os.O_CREATE | os.O_RDWR
	chunkSize := uint64(0)
	value := ""
	parent := &dfs.DFSObj{}
	dir, err := dfsInstance.Open(parent, dir1, mode, flags, chunkSize, value)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to open DFS object: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("Opened DFS object")


	// open or create a DFS file
	file1 := "file1"
	mode = syscall.S_IFREG | syscall.S_IWUSR | syscall.S_IRUSR
	flags = os.O_CREATE | os.O_RDWR
	chunkSize = uint64(0)
	value = ""
	file, err := dfsInstance.Open(dir, file1, mode, flags, chunkSize, value)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to open DFS object: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("Opened DFS file: ", file1)

	// create a scatter-gather list
	sgl := [][]byte{[]byte("Hello, World 2025!"), []byte("Hello, World 2026!")}
	err = dfsInstance.Write(file, sgl, 0, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to write to DFS object: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("Wrote to DFS file: ", file1)

	// read from the DFS file
	sgl = make([][]byte, 1)
	sgl[0] = make([]byte, 128)
	length, err := dfsInstance.Read(file, sgl, 0, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to read from DFS object: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("Read from DFS file: ", file1, " length: ", length, " data: ", string(sgl[0]))

	// release the DFS file
	err = dfsInstance.Release(file)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to close DFS object: %v\n", err)
		os.Exit(1)
	}

	// close the DFS dir
	err = dfsInstance.Release(dir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to close DFS object: %v\n", err)
		os.Exit(1)
	}

	// disconnect from the pool
	err = dfsInstance.Disconnect()
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to disconnect DFS: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("Disconnected from DFS")
	// finalize the DFS instance
	defer dfsInstance.Fini()
	fmt.Println("Finalized DFS")
}